import {
    ref,
    computed,
    //getCurrentInstance,
    //onBeforeMount,
    //setup
} from 'vue';
export default (tableColMetaListRef) => {
    const errTips = ref({})

    const needValidateMetaList = computed(() => {
        return tableColMetaListRef.value.filter(colMeta => (colMeta?.rules ?? []).length > 0);
    })
    const requiredMetaKeys = computed(() => {
        return needValidateMetaList.value.filter(colMeta => colMeta.rules.some(rule => rule.required)).map(el => el.key)
    })
    const validateMethods = computed(() => {
        const validateMethods = needValidateMetaList.value.map(el => {
            return {
                validateField: el.key,
                trigger: el.hasOwnProperty('trigger') ? el.trigger : (['Select'].includes(el.type) ? 'change' : 'blur'),
                validator: (rule, value, callback, tableRowData, tableColMetaList) => {
                    const validatorRule = el.rules.find(rule => rule && rule.hasOwnProperty('validator'));
                    if (!validatorRule) {
                        let errTip = ``

                        const isRequired = el.rules.some(rule => rule && rule.required);
                        const minRule = el.rules.find(rule => rule && rule.hasOwnProperty('min'));
                        const maxRule = el.rules.find(rule => rule && rule.hasOwnProperty('max'));
                        if (isRequired && ['', undefined, null].includes(value)) {
                            errTip = `${el.label}必填`
                        } else if (minRule && minRule.min >= 0 && `${value}`.length <= minRule.min) {
                            errTip = `${el.label}长度必须大于${minRule.min}`
                        } else if (maxRule && maxRule.max <= 0 && `${value}`.length <= maxRule.max) {
                            errTip = `${el.label}长度必须大于${maxRule.max}`
                        }
                        return callback(new Error(errTip))
                    } else {
                        return validatorRule['validator'](rule, value, callback, tableRowData, tableColMetaList)
                    }

                }
            }
        })
        const allValidateMethod = {}
        validateMethods.forEach(method => {
            allValidateMethod[method.validateField] = method
        })
        return allValidateMethod
    })

    const updateErrTip = (fieldName, errTip) => {
        if (errTip === "" && errTips.value.hasOwnProperty(fieldName)) {
            delete errTips.value[fieldName]
        } else errTips.value[fieldName] = errTip
    }
    return {
        requiredMetaKeys,
        validateMethods,
        errTips,
        updateErrTip
    }
}